import { ref } from "vue";
import { useCrudForm } from "@/composables/useCrudForm";
import { interviewFormConfig } from "../form-config";
import { formatDateTime } from "@/utils/xenUtils";
import SysHrInterviewRequestBillApi from "../api/index";
import commonApi from "@/api/common";
import type {
  ISysHrInterviewRequestBill,
  ISysHrInterviewRequestBillVm,
  IRecognizeIdentityCardRequest,
  IRecognizeIdentityCardResponse,
} from "../api/interface";

/**
 * 应聘申请单信息专用 Composable
 */
export function useInterviewInfo() {
  // 创建API实例
  const api = SysHrInterviewRequestBillApi();

  // 身份证有效期显示状态控制
  const idCardExpiryDisplayState = ref<"normal" | "long-term">("normal");

  // API配置
  const apiConfig = {
    search: api.search,
    get: api.get,
    add: api.add,
    edit: api.edit,
    delete: api.delete,
    // 单据编号接口 - 适配器处理类型差异
    getBillCode: async () => {
      const result = await api.getBillCode();
      return { Data: result.Data || "" };
    },
  };

  // 选项数据加载器
  const optionLoaders = {
    groupId: async () => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetParentsTree();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    jobPositionId: async () => {
      const commonApiInstance = commonApi();
      const result = await commonApiInstance.GetJobPositions();
      // 转换为useCrudForm期望的格式
      return result.map((item: any) => ({
        Value: item.Value,
        Text: item.Text,
      }));
    },
    recruitPublishRequestBillId: async () => {
      // 这里可以调用招聘发布单的API
      // 暂时返回空数组，等待具体API实现
      return [];
    },
  };

  /**
   * 搜索招聘发布单（自动补全用）
   */
  const searchRecruitBills = async (query: string) => {
    console.log('搜索招聘发布单被调用:', query);
    try {
      // 构建搜索参数 - 只需要IsExternalPublish参数
      const searchParams: any = {
        IsExternalPublish: true, // 只查询外部发布的招聘信息
      };
      console.log('搜索参数:', searchParams);

      // 使用新的招聘发布单搜索API
      const response = await api.searchRecruitPublishRequestBills(searchParams);
      console.log('API响应:', response);

      // 检查响应是否成功
      if (response.Code !== 200 || !response.Data) {
        console.warn('招聘发布单搜索API返回异常:', response.Msg || '未知错误');
        return [];
      }

      // 先根据用户输入的query进行前端过滤
      const filteredData = response.Data.filter((bill: any) => {
        const title = bill.Title || '';           // 岗位标题
        const billCode = bill.BillCode || '';     // 单据编号
        const groupName = bill.GroupName || '';   // 部门名称
        const orgName = bill.OrgName || '';       // 公司名称

        // 不区分大小写的模糊匹配
        const queryLower = query.toLowerCase();
        return title.toLowerCase().includes(queryLower) ||
          billCode.toLowerCase().includes(queryLower) ||
          groupName.toLowerCase().includes(queryLower) ||
          orgName.toLowerCase().includes(queryLower);
      });

      // 转换为自动补全组件期望的格式
      const result = filteredData.map((bill: any) => {
        const option = {
          value: bill.ID,
          text: bill.Title, // 使用API返回的Title字段，这将显示在输入框中
          subtitle: `单据编号: ${bill.BillCode} | ${bill.GroupName} | ${bill.OrgName}`, // 显示单据编号、部门和公司作为副标题
          // 扩展数据，包含招聘发布单的详细信息
          extData: {
            title: bill.Title,
            billCode: bill.BillCode,
            groupName: bill.GroupName,
            orgName: bill.OrgName,
            hireNumber: bill.HireNumber,
            salaryRange: bill.SalaryRange,
            ageRequirement: bill.AgeRequirement,
            educationRequirement: bill.EducationRequirement,
            genderRequirement: bill.GenderRequirement,
            majorRequirement: bill.MajorRequirement,
            jobRequirement: bill.JobRequirement,
            otherRequirement: bill.OtherRequirement,
            benefits: bill.Benefits,
            description: bill.Description,
            expectedDate: bill.ExpectedDate,
            isExternalPublish: bill.IsExternalPublish,
            billStatus: bill.BillStatus,
            workflowStatus: bill.WorkflowStatus,
            approver: bill.Approver,
            approvalTime: bill.ApprovalTime,
            createTime: bill.CreateTime,
            remark: bill.Remark,
          }
        };

        // 验证数据一致性
        if (option.text !== option.extData.title) {
          console.warn('数据映射警告:', {
            'option.text': option.text,
            'extData.title': option.extData.title,
            'bill.Title': bill.Title
          });
        }

        return option;
      });
      console.log('过滤后的搜索结果:', result);
      return result;
    } catch (error) {
      console.error('搜索招聘发布单失败:', error);
      return [];
    }
  };

  // 招聘发布单字段现在是只读的，不需要搜索API
  // 为recruitPublishRequestBillId字段配置searchApi
  // if (interviewFormConfig.recruitPublishRequestBillId) {
  //   interviewFormConfig.recruitPublishRequestBillId.searchApi = searchRecruitBills;
  // }

  // 使用通用CRUD表单
  const crudForm = useCrudForm<ISysHrInterviewRequestBill, ISysHrInterviewRequestBillVm>(
    interviewFormConfig,
    apiConfig,
    optionLoaders
  );

  /**
   * 转换表单数据为API格式（新增）
   */
  const convertFormDataToApiFormatForCreate = (): ISysHrInterviewRequestBillVm => {
    return {
      Entity: {
        RecruitPoolId: null,
        RecruitNo: null,
        ArrivalDate: crudForm.formData.arrivalDate ? new Date(crudForm.formData.arrivalDate) : null,
        CurrentSalary: crudForm.formData.currentSalary || null,
        ExpectedSalary: crudForm.formData.expectedSalary || null,
        WorkExperience: crudForm.formData.workExperience || null,
        InitialTestTime: null,
        InitialResult: null,
        InitialComment: null,
        ReExamTime: null,
        ReExamResult: null,
        ReExamComment: null,
        FinalResult: null,
        FinalRemark: null,
        RejectReason: null,
        BillCode: crudForm.formData.billCode || null,
        BillStatus: null,
        WorkflowStatus: null,
        Remark: crudForm.formData.remark || null,
        Approver: null,
        ApprovalTime: null,
        Name: crudForm.formData.name || null,
        StaffNo: null,
        BirthDate: crudForm.formData.birthDate ? new Date(crudForm.formData.birthDate) : null,
        Age: null,
        Gender: crudForm.pickerValues.gender || null,
        Ethnicity: crudForm.pickerValues.ethnicity || null,
        HighestEducation: crudForm.pickerValues.highestEducation || null,
        MaritalStatus: crudForm.pickerValues.maritalStatus || null,
        PhotoId: (crudForm.formData.photoId && typeof crudForm.formData.photoId === 'string' && crudForm.formData.photoId.trim() !== "") ? crudForm.formData.photoId : null,
        IdCardNo: crudForm.formData.idCardNo || null,
        IdCardFrontPhotoId: (crudForm.formData.idCardFrontPhotoId && typeof crudForm.formData.idCardFrontPhotoId === 'string' && crudForm.formData.idCardFrontPhotoId.trim() !== "") ? crudForm.formData.idCardFrontPhotoId : null,
        IdCardBackPhotoId: (crudForm.formData.idCardBackPhotoId && typeof crudForm.formData.idCardBackPhotoId === 'string' && crudForm.formData.idCardBackPhotoId.trim() !== "") ? crudForm.formData.idCardBackPhotoId : null,
        IdCardExpiryDate: crudForm.formData.idCardExpiryDate ? new Date(crudForm.formData.idCardExpiryDate) : null,
        HouseholdRegistration: crudForm.formData.householdRegistration || null,
        NativePlace: crudForm.formData.nativePlace || null,
        PoliticalStatus: crudForm.pickerValues.politicalStatus || null,
        PartyJoinDate: crudForm.formData.partyJoinDate ? new Date(crudForm.formData.partyJoinDate) : null,
        PartyBranch: crudForm.formData.partyBranch || null,
        ArchiveLocation: null,
        ArchiveNo: null,
        ArchiveTransferOutDate: null,
        ArchiveTransferInDate: null,
        HomeAddress: crudForm.formData.homeAddress || null,
        Phone: crudForm.formData.phone || null,
        Email: crudForm.formData.email || null,
        SalaryBank: null,
        SalaryAccount: null,
        BonusBank: null,
        BonusAccount: null,
        OrgId: null,
        GroupId: null,
        JobPositionId: null,
        ResumeId: null,
        HireDate: null,
        ConfirmationDate: null,
        EmploymentType: crudForm.pickerValues.employmentType || null,
        ContractType: null,
        ContractNo: null,
        ContractStartDate: null,
        ContractEndDate: null,
        ResignationDate: null,
        ResignationReason: null,
        ResignationType: null,
        State: null,
        BloodType: null,
        Hobbies: null,
        IsVeteran: crudForm.pickerValues.isVeteran === "是" ? "true" : crudForm.pickerValues.isVeteran === "否" ? "false" : null,
        VeteranCertificateId: (crudForm.formData.veteranCertificateId && typeof crudForm.formData.veteranCertificateId === 'string' && crudForm.formData.veteranCertificateId.trim() !== "") ? crudForm.formData.veteranCertificateId : null,
        Height: crudForm.formData.height ? Number(crudForm.formData.height) : null,
        Weight: crudForm.formData.weight ? Number(crudForm.formData.weight) : null,
        FertilityStatus: crudForm.pickerValues.fertilityStatus || null,
        MajorCategory: crudForm.pickerValues.majorCategory || null,
        MajorName: crudForm.formData.majorName || null,
        HasRelativeInCompany: crudForm.pickerValues.hasRelativeInCompany === "是" ? true : crudForm.pickerValues.hasRelativeInCompany === "否" ? false : null,
        RelativeName: crudForm.formData.relativeName || null,
        RelationshipType: crudForm.pickerValues.relationshipType || null,
        IsLaborRelationshipTerminated: crudForm.pickerValues.isLaborRelationshipTerminated === "是" ? true : crudForm.pickerValues.isLaborRelationshipTerminated === "否" ? false : null,
        WorkYears: null,
        CompanyYears: null,
        JoinWorkDate: crudForm.formData.joinWorkDate ? new Date(crudForm.formData.joinWorkDate) : null,
        ArchiveAgeDate: null,
        Order: null,
        RecruitPublishRequestBillId: (crudForm.pickerValues.recruitPublishRequestBillId && typeof crudForm.pickerValues.recruitPublishRequestBillId === 'string' && crudForm.pickerValues.recruitPublishRequestBillId.trim() !== "") ? crudForm.pickerValues.recruitPublishRequestBillId : null,
      },
      ActionName: null,
      IsMyApprove: false,
      Remark: null,
    };
  };

  /**
   * 转换表单数据为API格式（编辑）
   */
  const convertFormDataToApiFormatForEdit = (): ISysHrInterviewRequestBillVm => {
    const originalData = crudForm.originalData.value;
    if (!originalData) {
      throw new Error("原始数据不存在");
    }

    return {
      Entity: {
        ID: (originalData.ID && typeof originalData.ID === 'string' && originalData.ID.trim() !== "") ? originalData.ID : null,
        RecruitPoolId: (crudForm.pickerValues.recruitPublishRequestBillId && typeof crudForm.pickerValues.recruitPublishRequestBillId === 'string' && crudForm.pickerValues.recruitPublishRequestBillId.trim() !== "")
          ? crudForm.pickerValues.recruitPublishRequestBillId
          : (originalData.RecruitPoolId && typeof originalData.RecruitPoolId === 'string' && originalData.RecruitPoolId.trim() !== "" ? originalData.RecruitPoolId : null),
        RecruitNo: originalData.RecruitNo,
        ArrivalDate: crudForm.formData.arrivalDate ? new Date(crudForm.formData.arrivalDate) : originalData.ArrivalDate,
        CurrentSalary: crudForm.formData.currentSalary || originalData.CurrentSalary,
        ExpectedSalary: crudForm.formData.expectedSalary || originalData.ExpectedSalary,
        WorkExperience: crudForm.formData.workExperience || originalData.WorkExperience,
        InitialTestTime: originalData.InitialTestTime,
        InitialResult: originalData.InitialResult,
        InitialComment: originalData.InitialComment,
        ReExamTime: originalData.ReExamTime,
        ReExamResult: originalData.ReExamResult,
        ReExamComment: originalData.ReExamComment,
        FinalResult: originalData.FinalResult,
        FinalRemark: originalData.FinalRemark,
        RejectReason: originalData.RejectReason,
        BillCode: crudForm.formData.billCode || originalData.BillCode,
        BillStatus: originalData.BillStatus,
        WorkflowStatus: originalData.WorkflowStatus,
        Remark: crudForm.formData.remark || originalData.Remark,
        Approver: originalData.Approver,
        ApprovalTime: originalData.ApprovalTime,
        Name: crudForm.formData.name || originalData.Name,
        StaffNo: originalData.StaffNo,
        BirthDate: crudForm.formData.birthDate ? new Date(crudForm.formData.birthDate) : originalData.BirthDate,
        Age: originalData.Age,
        Gender: crudForm.pickerValues.gender || originalData.Gender,
        Ethnicity: crudForm.pickerValues.ethnicity || originalData.Ethnicity,
        HighestEducation: crudForm.pickerValues.highestEducation || originalData.HighestEducation,
        MaritalStatus: crudForm.pickerValues.maritalStatus || originalData.MaritalStatus,
        PhotoId: (crudForm.formData.photoId && typeof crudForm.formData.photoId === 'string' && crudForm.formData.photoId.trim() !== "")
          ? crudForm.formData.photoId
          : (originalData.PhotoId && typeof originalData.PhotoId === 'string' && originalData.PhotoId.trim() !== "" ? originalData.PhotoId : null),
        IdCardNo: crudForm.formData.idCardNo || originalData.IdCardNo,
        IdCardFrontPhotoId: (crudForm.formData.idCardFrontPhotoId && typeof crudForm.formData.idCardFrontPhotoId === 'string' && crudForm.formData.idCardFrontPhotoId.trim() !== "")
          ? crudForm.formData.idCardFrontPhotoId
          : (originalData.IdCardFrontPhotoId && typeof originalData.IdCardFrontPhotoId === 'string' && originalData.IdCardFrontPhotoId.trim() !== "" ? originalData.IdCardFrontPhotoId : null),
        IdCardBackPhotoId: (crudForm.formData.idCardBackPhotoId && typeof crudForm.formData.idCardBackPhotoId === 'string' && crudForm.formData.idCardBackPhotoId.trim() !== "")
          ? crudForm.formData.idCardBackPhotoId
          : (originalData.IdCardBackPhotoId && typeof originalData.IdCardBackPhotoId === 'string' && originalData.IdCardBackPhotoId.trim() !== "" ? originalData.IdCardBackPhotoId : null),
        IdCardExpiryDate: crudForm.formData.idCardExpiryDate ? new Date(crudForm.formData.idCardExpiryDate) : originalData.IdCardExpiryDate,
        HouseholdRegistration: crudForm.formData.householdRegistration || originalData.HouseholdRegistration,
        NativePlace: crudForm.formData.nativePlace || originalData.NativePlace,
        PoliticalStatus: crudForm.pickerValues.politicalStatus || originalData.PoliticalStatus,
        PartyJoinDate: crudForm.formData.partyJoinDate ? new Date(crudForm.formData.partyJoinDate) : originalData.PartyJoinDate,
        PartyBranch: crudForm.formData.partyBranch || originalData.PartyBranch,
        ArchiveLocation: originalData.ArchiveLocation,
        ArchiveNo: originalData.ArchiveNo,
        ArchiveTransferOutDate: originalData.ArchiveTransferOutDate,
        ArchiveTransferInDate: originalData.ArchiveTransferInDate,
        HomeAddress: crudForm.formData.homeAddress || originalData.HomeAddress,
        Phone: crudForm.formData.phone || originalData.Phone,
        Email: crudForm.formData.email || originalData.Email,
        SalaryBank: originalData.SalaryBank,
        SalaryAccount: originalData.SalaryAccount,
        BonusBank: originalData.BonusBank,
        BonusAccount: originalData.BonusAccount,
        OrgId: (originalData.OrgId && typeof originalData.OrgId === 'string' && originalData.OrgId.trim() !== "" ? originalData.OrgId : null),
        GroupId: (originalData.GroupId && typeof originalData.GroupId === 'string' && originalData.GroupId.trim() !== "" ? originalData.GroupId : null),
        JobPositionId: (originalData.JobPositionId && typeof originalData.JobPositionId === 'string' && originalData.JobPositionId.trim() !== "" ? originalData.JobPositionId : null),
        ResumeId: (originalData.ResumeId && typeof originalData.ResumeId === 'string' && originalData.ResumeId.trim() !== "" ? originalData.ResumeId : null),
        HireDate: originalData.HireDate,
        ConfirmationDate: originalData.ConfirmationDate,
        EmploymentType: crudForm.pickerValues.employmentType || originalData.EmploymentType,
        ContractType: originalData.ContractType,
        ContractNo: originalData.ContractNo,
        ContractStartDate: originalData.ContractStartDate,
        ContractEndDate: originalData.ContractEndDate,
        ResignationDate: originalData.ResignationDate,
        ResignationReason: originalData.ResignationReason,
        ResignationType: originalData.ResignationType,
        State: originalData.State,
        BloodType: originalData.BloodType,
        Hobbies: originalData.Hobbies,
        IsVeteran: crudForm.pickerValues.isVeteran === "是" ? "true" : crudForm.pickerValues.isVeteran === "否" ? "false" : originalData.IsVeteran,
        VeteranCertificateId: (crudForm.formData.veteranCertificateId && typeof crudForm.formData.veteranCertificateId === 'string' && crudForm.formData.veteranCertificateId.trim() !== "")
          ? crudForm.formData.veteranCertificateId
          : (originalData.VeteranCertificateId && typeof originalData.VeteranCertificateId === 'string' && originalData.VeteranCertificateId.trim() !== "" ? originalData.VeteranCertificateId : null),
        Height: crudForm.formData.height ? Number(crudForm.formData.height) : originalData.Height,
        Weight: crudForm.formData.weight ? Number(crudForm.formData.weight) : originalData.Weight,
        FertilityStatus: crudForm.pickerValues.fertilityStatus || originalData.FertilityStatus,
        MajorCategory: crudForm.pickerValues.majorCategory || originalData.MajorCategory,
        MajorName: crudForm.formData.majorName || originalData.MajorName,
        HasRelativeInCompany: crudForm.pickerValues.hasRelativeInCompany === "是" ? true : crudForm.pickerValues.hasRelativeInCompany === "否" ? false : originalData.HasRelativeInCompany,
        RelativeName: crudForm.formData.relativeName || originalData.RelativeName,
        RelationshipType: crudForm.pickerValues.relationshipType || originalData.RelationshipType,
        IsLaborRelationshipTerminated: crudForm.pickerValues.isLaborRelationshipTerminated === "是" ? true : crudForm.pickerValues.isLaborRelationshipTerminated === "否" ? false : originalData.IsLaborRelationshipTerminated,
        WorkYears: originalData.WorkYears,
        CompanyYears: originalData.CompanyYears,
        JoinWorkDate: crudForm.formData.joinWorkDate ? new Date(crudForm.formData.joinWorkDate) : originalData.JoinWorkDate,
        ArchiveAgeDate: originalData.ArchiveAgeDate,
        Order: originalData.Order,
        RecruitPublishRequestBillId: (crudForm.pickerValues.recruitPublishRequestBillId && typeof crudForm.pickerValues.recruitPublishRequestBillId === 'string' && crudForm.pickerValues.recruitPublishRequestBillId.trim() !== "")
          ? crudForm.pickerValues.recruitPublishRequestBillId
          : (originalData.RecruitPublishRequestBillId && typeof originalData.RecruitPublishRequestBillId === 'string' && originalData.RecruitPublishRequestBillId.trim() !== "" ? originalData.RecruitPublishRequestBillId : null),
      },
      ActionName: null,
      IsMyApprove: false,
      Remark: null,
    };
  };

  /**
   * 字段映射配置（API字段路径到表单字段的映射）
   */
  const fieldMapping = {
    // 应聘信息
    recruitPublishRequestBillId: "RecruitPublishRequestBillId",
    arrivalDate: "ArrivalDate",
    workExperience: "WorkExperience",
    currentSalary: "CurrentSalary",
    expectedSalary: "ExpectedSalary",
    initialTestTime: "InitialTestTime",
    initialResult: "InitialResult",
    initialComment: "InitialComment",
    reExamTime: "ReExamTime",
    reExamResult: "ReExamResult",
    reExamComment: "ReExamComment",
    finalResult: "FinalResult",
    finalRemark: "FinalRemark",
    rejectReason: "RejectReason",

    // 单据信息
    billCode: "BillCode",
    billStatus: "BillStatus",
    workflowStatus: "WorkflowStatus",
    remark: "Remark",

    // 基本信息
    name: "Name",
    gender: "Gender",
    birthDate: "BirthDate",
    ethnicity: "Ethnicity",
    height: "Height",
    weight: "Weight",
    highestEducation: "HighestEducation",
    majorCategory: "MajorCategory",
    majorName: "MajorName",
    maritalStatus: "MaritalStatus",
    fertilityStatus: "FertilityStatus",
    photoId: "PhotoId",
    isVeteran: "IsVeteran",
    veteranCertificateId: "VeteranCertificateId",
    hasRelativeInCompany: "HasRelativeInCompany",
    relativeName: "RelativeName",
    relationshipType: "RelationshipType",
    isLaborRelationshipTerminated: "IsLaborRelationshipTerminated",

    // 身份信息
    idCardNo: "IdCardNo",
    idCardFrontPhotoId: "IdCardFrontPhotoId",
    idCardBackPhotoId: "IdCardBackPhotoId",
    idCardExpiryDate: "IdCardExpiryDate",

    // 户籍信息
    householdRegistration: "HouseholdRegistration",
    nativePlace: "NativePlace",
    politicalStatus: "PoliticalStatus",
    partyJoinDate: "PartyJoinDate",
    partyBranch: "PartyBranch",

    // 联系方式
    homeAddress: "HomeAddress",
    phone: "Phone",
    email: "Email",

    // 工作信息
    orgId: "Org.GroupName",
    groupId: "Group.GroupName",
    jobPositionId: "JobPosition.JobPositionName",
    joinWorkDate: "JoinWorkDate",
    employmentType: "EmploymentType",

    // 流程信息
    approver: "Approver",
    approvalTime: "ApprovalTime",
  };

  /**
   * 加载应聘申请单详情数据
   */
  const loadInterviewDetail = async (id: string): Promise<{ success: boolean; isMyApprove?: boolean }> => {
    try {
      // 直接调用API获取完整响应
      const response = await api.get(id);

      if (response && response.Entity) {
        const detail = response.Entity;

        // 设置原始数据
        crudForm.originalData.value = detail;

        // 检查原始数据中的日期字段
        const dateFields = ["ApprovalTime", "ArrivalDate", "BirthDate", "IdCardExpiryDate", "PartyJoinDate", "JoinWorkDate", "InitialTestTime", "ReExamTime"];
        dateFields.forEach(field => {
          if ((detail as any)[field]) {
            console.log(`原始数据中的日期字段 ${field}:`, (detail as any)[field]);
          }
        });

        // 先使用通用转换
        crudForm.convertApiDataToFormData(detail, fieldMapping);

        // 添加特殊处理，确保选择器字段正确映射
        await ensurePickerFieldsMapping(detail);

        return {
          success: true,
          isMyApprove: response.IsMyApprove || false
        };
      }
      return { success: false };
    } catch (error) {
      console.error("获取入职申请单详情失败:", error);
      return { success: false };
    }
  };

  /**
   * 确保选择器字段正确映射
   */
  const ensurePickerFieldsMapping = async (apiData: any) => {
    // 处理招聘发布单
    if (apiData.RecruitPublishRequestBillId) {
      // 设置ID到pickerValues中（用于提交）
      crudForm.pickerValues.recruitPublishRequestBillId = apiData.RecruitPublishRequestBillId;

      // 尝试通过搜索API获取招聘发布单的详细信息，并预设到options中让XenAutoComplete能正确显示
      try {
        // 使用搜索API获取所有外部发布的招聘发布单信息
        const searchResponse = await api.searchRecruitPublishRequestBills({
          IsExternalPublish: true, // 只查询外部发布的招聘信息
        });

        if (searchResponse.Code === 200 && searchResponse.Data) {
          // 查找匹配的招聘发布单
          const matchedBill = searchResponse.Data.find((bill: any) => bill.ID === apiData.RecruitPublishRequestBillId);
          if (matchedBill) {
            // 设置显示文本到formData中
            crudForm.formData.recruitPublishRequestBillId = matchedBill.Title;
            // 将匹配的选项添加到field的optionsData中，这样XenAutoComplete就能正确显示文本
            if (interviewFormConfig.recruitPublishRequestBillId) {
              interviewFormConfig.recruitPublishRequestBillId.optionsData = [{
                value: matchedBill.ID,
                text: matchedBill.Title,
                subtitle: `单据编号: ${matchedBill.BillCode} | ${matchedBill.GroupName} | ${matchedBill.OrgName}`,
                extData: {
                  title: matchedBill.Title,
                  billCode: matchedBill.BillCode,
                  groupName: matchedBill.GroupName,
                  orgName: matchedBill.OrgName,
                  hireNumber: matchedBill.HireNumber,
                  salaryRange: matchedBill.SalaryRange,
                  ageRequirement: matchedBill.AgeRequirement,
                  educationRequirement: matchedBill.EducationRequirement,
                  genderRequirement: matchedBill.GenderRequirement,
                  majorRequirement: matchedBill.MajorRequirement,
                  jobRequirement: matchedBill.JobRequirement,
                  otherRequirement: matchedBill.OtherRequirement,
                  benefits: matchedBill.Benefits,
                  description: matchedBill.Description,
                  expectedDate: matchedBill.ExpectedDate,
                  isExternalPublish: matchedBill.IsExternalPublish,
                  billStatus: matchedBill.BillStatus,
                  workflowStatus: matchedBill.WorkflowStatus,
                  approver: matchedBill.Approver,
                  approvalTime: matchedBill.ApprovalTime,
                  createTime: matchedBill.CreateTime,
                  remark: matchedBill.Remark,
                }
              }];
            }
            console.log('成功为编辑模式设置招聘发布单选项:', matchedBill.Title);
          } else {
            console.warn('未找到匹配的招聘发布单:', apiData.RecruitPublishRequestBillId);
          }
        }
      } catch (error) {
        console.error('获取招聘发布单信息失败:', error);
      }
    }

    // 处理单据编号
    if (apiData.BillCode) {
      crudForm.formData.billCode = apiData.BillCode;
    }

    // 处理单据状态
    if (apiData.BillStatus !== undefined) {
      const statusText = apiData.BillStatus === "草稿" ? "草稿" : "正文";
      crudForm.formData.billStatus = statusText;
      crudForm.pickerValues.billStatus = apiData.BillStatus.toString();
    }

    // 处理工作流状态显示
    if (apiData.WorkflowStatus !== undefined) {
      crudForm.formData.workflowStatus = apiData.WorkflowStatus || "";
    }

    // 处理性别
    if (apiData.Gender !== undefined) {
      const genderText = apiData.Gender === 1 ? "男" : apiData.Gender === 2 ? "女" : "";
      crudForm.formData.gender = genderText;
      crudForm.pickerValues.gender = genderText;
    }

    // 处理学历 - 直接使用文字文本
    if (apiData.HighestEducation !== undefined) {
      const educationText = apiData.HighestEducation || "";
      crudForm.formData.highestEducation = educationText;
      crudForm.pickerValues.highestEducation = educationText;
    }

    // 处理民族 - 直接使用文字文本
    if (apiData.Ethnicity !== undefined) {
      const ethnicityText = apiData.Ethnicity || "";
      crudForm.formData.ethnicity = ethnicityText;
      crudForm.pickerValues.ethnicity = ethnicityText;
    }

    // 处理婚姻状况 - 直接使用文字文本
    if (apiData.MaritalStatus !== undefined) {
      const maritalText = apiData.MaritalStatus || "";
      crudForm.formData.maritalStatus = maritalText;
      crudForm.pickerValues.maritalStatus = maritalText;
    }

    // 处理政治面貌 - 直接使用文字文本
    if (apiData.PoliticalStatus !== undefined) {
      const politicalText = apiData.PoliticalStatus || "";
      crudForm.formData.politicalStatus = politicalText;
      crudForm.pickerValues.politicalStatus = politicalText;
    }

    // 处理用工形式 - 直接使用文字文本
    if (apiData.EmploymentType !== undefined) {
      const employmentText = apiData.EmploymentType || "";
      crudForm.formData.employmentType = employmentText;
      crudForm.pickerValues.employmentType = employmentText;
    }

    // 处理退伍军人字段
    if (apiData.IsVeteran !== undefined) {
      const isVeteranText = apiData.IsVeteran === "true" || apiData.IsVeteran === true ? "是" : "否";
      crudForm.formData.isVeteran = isVeteranText;
      crudForm.pickerValues.isVeteran = isVeteranText;
    }

    // 处理退伍证照片
    if (apiData.VeteranCertificateId) {
      crudForm.formData.veteranCertificateId = apiData.VeteranCertificateId;
    }

    // 处理身高
    if (apiData.Height !== undefined) {
      crudForm.formData.height = apiData.Height ? apiData.Height.toString() : "";
    }

    // 处理体重
    if (apiData.Weight !== undefined) {
      crudForm.formData.weight = apiData.Weight ? apiData.Weight.toString() : "";
    }

    // 处理生育状况 - 直接使用文字文本
    if (apiData.FertilityStatus !== undefined) {
      const fertilityText = apiData.FertilityStatus || "";
      crudForm.formData.fertilityStatus = fertilityText;
      crudForm.pickerValues.fertilityStatus = fertilityText;
    }

    // 处理专业大类 - 直接使用文字文本
    if (apiData.MajorCategory !== undefined) {
      const majorCategoryText = apiData.MajorCategory || "";
      crudForm.formData.majorCategory = majorCategoryText;
      crudForm.pickerValues.majorCategory = majorCategoryText;
    }

    // 处理专业名称
    if (apiData.MajorName !== undefined) {
      crudForm.formData.majorName = apiData.MajorName || "";
    }

    // 处理亲属关系 - 布尔值转换为中文
    if (apiData.HasRelativeInCompany !== undefined) {
      const hasRelativeText = apiData.HasRelativeInCompany === true || apiData.HasRelativeInCompany === "true" ? "是" : "否";
      crudForm.formData.hasRelativeInCompany = hasRelativeText;
      crudForm.pickerValues.hasRelativeInCompany = hasRelativeText;
    }

    // 处理亲属姓名
    if (apiData.RelativeName !== undefined) {
      crudForm.formData.relativeName = apiData.RelativeName || "";
    }

    // 处理亲属关系类型 - 直接使用文字文本
    if (apiData.RelationshipType !== undefined) {
      const relationshipText = apiData.RelationshipType || "";
      crudForm.formData.relationshipType = relationshipText;
      crudForm.pickerValues.relationshipType = relationshipText;
    }

    // 处理是否解除劳务合同 - 布尔值转换为中文
    if (apiData.IsLaborRelationshipTerminated !== undefined) {
      const isLaborTerminatedText = apiData.IsLaborRelationshipTerminated === true || apiData.IsLaborRelationshipTerminated === "true" ? "是" : "否";
      crudForm.formData.isLaborRelationshipTerminated = isLaborTerminatedText;
      crudForm.pickerValues.isLaborRelationshipTerminated = isLaborTerminatedText;
    }

    // 处理日期字段格式化
    const dateFields = [
      { field: "ArrivalDate", formField: "arrivalDate" },
      { field: "BirthDate", formField: "birthDate" },
      { field: "IdCardExpiryDate", formField: "idCardExpiryDate" },
      { field: "PartyJoinDate", formField: "partyJoinDate" },
      { field: "JoinWorkDate", formField: "joinWorkDate" },
      { field: "ApprovalTime", formField: "approvalTime" },
      { field: "InitialTestTime", formField: "initialTestTime" },
      { field: "ReExamTime", formField: "reExamTime" },
    ];

    dateFields.forEach(({ field, formField }) => {
      if (apiData[field]) {
        if (formField === "approvalTime" || formField === "initialTestTime" || formField === "reExamTime") {
          // 时间字段包含时分
          crudForm.formData[formField] = formatDateTime(apiData[field]);
        } else if (formField === "idCardExpiryDate") {
          // 身份证有效期特殊处理：检查是否为长期有效
          const formattedDateTime = formatDateTime(apiData[field]);
          const dateString = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
          
          if (dateString) {
            try {
              const parsedDate = new Date(dateString);
              if (!isNaN(parsedDate.getTime())) {
                // 检查日期是否超过50年（约18250天）
                const currentDate = new Date();
                const daysDifference = Math.abs(
                  (parsedDate.getTime() - currentDate.getTime()) /
                    (1000 * 60 * 60 * 24),
                );

                if (daysDifference > 18250) {
                  // 如果超过50年，保存原始日期但设置显示状态为"长期有效"
                  crudForm.formData[formField] = dateString; // 保存原始日期用于数据提交
                  idCardExpiryDisplayState.value = "long-term"; // 设置显示状态
                } else {
                  // 正常日期
                  crudForm.formData[formField] = dateString;
                  idCardExpiryDisplayState.value = "normal"; // 重置显示状态为正常
                }
              } else {
                crudForm.formData[formField] = dateString;
                idCardExpiryDisplayState.value = "normal";
              }
            } catch (error) {
              crudForm.formData[formField] = dateString;
              idCardExpiryDisplayState.value = "normal";
            }
          }
        } else {
          // 其他日期字段只包含年月日
          const formattedDateTime = formatDateTime(apiData[field]);
          crudForm.formData[formField] = formattedDateTime ? formattedDateTime.split(' ')[0] : '';
        }
      }
    });

    // 处理审批人
    if (apiData.Approver) {
      crudForm.formData.approver = apiData.Approver;
    }
  };

  /**
   * 创建应聘申请单（两步提交流程）
   * 第一步：调用Add接口保存草稿
   * 第二步：调用Edit接口提交
   */
  const createInterview = async (): Promise<{
    success: boolean;
    data?: ISysHrInterviewRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    try {
      // 第一步：调用Add接口保存草稿
      const apiData = convertFormDataToApiFormatForCreate();
      const addResult = await crudForm.create(apiData);

      if (!addResult || !addResult.ID) {
        return {
          success: false,
          validation: validationResult,
          error: "保存草稿失败，请重试"
        };
      }

      // 第二步：调用Edit接口进行提交
      // 设置原始数据为第一步返回的结果，用于Edit接口
      crudForm.originalData.value = addResult;

      // 创建编辑数据格式进行提交
      const editApiData = convertFormDataToApiFormatForEdit();

      const editResult = await crudForm.update(editApiData);

      if (!editResult) {
        return {
          success: false,
          validation: validationResult,
          error: "提交失败，数据已保存为草稿，请稍后重试"
        };
      }

      return {
        success: true,
        data: editResult,
        validation: validationResult
      };

    } catch (error) {
      console.error("创建应聘申请单失败:", error);
      return {
        success: false,
        validation: validationResult,
        error: "提交过程中发生错误，请重试"
      };
    }
  };

  /**
   * 保存应聘申请单（编辑）
   */
  const saveInterview = async (): Promise<{
    success: boolean;
    data?: ISysHrInterviewRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    // 验证关键数据
    if (!crudForm.originalData.value) {
      return {
        success: false,
        error: "原始数据丢失，请重新加载页面",
        validation: validationResult
      };
    }

    const apiData = convertFormDataToApiFormatForEdit();
    const result = await crudForm.update(apiData);

    return {
      success: result !== null,
      data: result || undefined,
      validation: validationResult
    };
  };

  /**
   * 简单保存应聘申请单（新增 - 只调用Add接口）
   */
  const saveInterviewSimple = async (): Promise<{
    success: boolean;
    data?: ISysHrInterviewRequestBill;
    validation?: { valid: boolean; errors: Record<string, string>; firstErrorMessage?: string };
    error?: string;
  }> => {
    const validationResult = crudForm.validateAllFieldsWithDetails();

    if (!validationResult.valid) {
      return {
        success: false,
        validation: validationResult
      };
    }

    try {
      // 只调用Add接口保存
      const apiData = convertFormDataToApiFormatForCreate();
      const result = await crudForm.create(apiData);

      if (!result || !result.ID) {
        return {
          success: false,
          validation: validationResult,
          error: "保存失败，请重试"
        };
      }

      return {
        success: true,
        data: result,
        validation: validationResult
      };

    } catch (error) {
      console.error("保存应聘申请单失败:", error);
      return {
        success: false,
        validation: validationResult,
        error: "保存过程中发生错误，请重试"
      };
    }
  };

  /**
   * 重写 initializeOptions 方法，同时更新相关数据
   */
  const initializeOptions = async (): Promise<boolean> => {
    // 先调用原始的 initializeOptions
    const result = await crudForm.initializeOptions();

    return result;
  };

  /**
   * 身份证识别功能
   * @param imageId 身份证图片ID
   * @param cardType 身份证类型 front（正面）、back（反面）
   */
  const recognizeIdentityCard = async (
    imageId: string,
    cardType: "front" | "back",
  ) => {
    try {
      uni.showLoading({
        title: "正在识别身份证信息...",
        mask: true,
      });

      const response = await api.recognizeIdentityCard({
        ImageId: imageId,
        CardType: cardType,
      });

      uni.hideLoading();

      if (response.Code === 200 && response.Data) {
        const data = response.Data;

        if (cardType === "front") {
          // 验证是否确实是身份证正面（正面应该包含姓名、身份证号等基本信息）
          const hasFrontInfo =
            data.Name || data.IdNumber || data.Gender || data.BirthDate;
          const hasBackInfo = data.IssuingAuthority || data.ValidPeriod;

          if (!hasFrontInfo && hasBackInfo) {
            // 用户上传了身份证反面，但选择的是正面
            // 清理错误上传的图片数据
            crudForm.formData.idCardFrontPhotoId = null;

            uni.showModal({
              title: "上传错误",
              content:
                "检测到您上传的是身份证反面，但当前需要上传身份证正面。图片已清除，请重新选择身份证正面照片上传。",
              confirmText: "重新上传",
              showCancel: false,
            });
            return;
          }

          if (!hasFrontInfo) {
            // 无法识别出正面信息
            // 清理可能有问题的图片数据
            crudForm.formData.idCardFrontPhotoId = null;

            uni.showModal({
              title: "识别异常",
              content:
                "无法从图片中识别出身份证正面信息。图片已清除，请重新上传。\n\n请确认并检查：\n1. 是否上传了正确的身份证正面\n2. 照片清晰完整\n3. 无反光、遮挡或模糊\n4. 身份证在照片中居中显示",
              confirmText: "我知道了",
              showCancel: false,
            });
            return;
          }

          // 身份证正面信息
          if (data.Name) {
            crudForm.formData.name = data.Name;
          }
          if (data.Gender) {
            // 直接使用性别文字
            crudForm.formData.gender = data.Gender;
            crudForm.pickerValues.gender = data.Gender;
          }
          if (data.Nationality) {
            // 根据民族名称设置对应的文字值
            const ethnicityMap: Record<string, string> = {
              汉: "汉族",
              汉族: "汉族",
              壮: "壮族",
              壮族: "壮族",
              满: "满族",
              满族: "满族",
              回: "回族",
              回族: "回族",
              蒙古: "蒙古族",
              蒙古族: "蒙古族",
            };
            const ethnicityValue = ethnicityMap[data.Nationality] || "汉族"; // 默认为汉族
            crudForm.formData.ethnicity = ethnicityValue;
            crudForm.pickerValues.ethnicity = ethnicityValue;
          }
          if (data.BirthDate) {
            // 处理各种可能的日期格式
            const birthDateStr = data.BirthDate.toString();
            let parsedDate: Date | null = null;

            try {
              // 情况1: 中文格式 (如：1990年10月1日)
              if (/^\d{4}年\d{1,2}月\d{1,2}日$/.test(birthDateStr)) {
                const match = birthDateStr.match(
                  /^(\d{4})年(\d{1,2})月(\d{1,2})日$/,
                );
                if (match) {
                  const year = parseInt(match[1]);
                  const month = parseInt(match[2]);
                  const day = parseInt(match[3]);
                  parsedDate = new Date(year, month - 1, day);
                }
              }
              // 情况2: YYYYMMDD 格式 (如：20130506)
              else if (/^\d{8}$/.test(birthDateStr)) {
                const year = birthDateStr.substring(0, 4);
                const month = birthDateStr.substring(4, 6);
                const day = birthDateStr.substring(6, 8);
                parsedDate = new Date(
                  parseInt(year),
                  parseInt(month) - 1,
                  parseInt(day),
                );
              }
              // 情况3: YYYY-MM-DD 格式
              else if (/^\d{4}-\d{2}-\d{2}$/.test(birthDateStr)) {
                parsedDate = new Date(birthDateStr + "T00:00:00");
              }
              // 情况4: YYYY.MM.DD 格式
              else if (/^\d{4}\.\d{2}\.\d{2}$/.test(birthDateStr)) {
                const normalizedDate = birthDateStr.replace(/\./g, "-");
                parsedDate = new Date(normalizedDate + "T00:00:00");
              }
              // 情况5: YYYY/MM/DD 格式
              else if (/^\d{4}\/\d{2}\/\d{2}$/.test(birthDateStr)) {
                const normalizedDate = birthDateStr.replace(/\//g, "-");
                parsedDate = new Date(normalizedDate + "T00:00:00");
              }
              // 情况6: 其他格式，尝试直接解析
              else {
                parsedDate = new Date(birthDateStr);
              }

              // 验证日期是否有效
              if (parsedDate && !isNaN(parsedDate.getTime())) {
                // 格式化日期为 YYYY-MM-DD 格式显示
                const year = parsedDate.getFullYear();
                const month = String(parsedDate.getMonth() + 1).padStart(2, "0");
                const day = String(parsedDate.getDate()).padStart(2, "0");
                const dateString = `${year}-${month}-${day}`;
                crudForm.formData.birthDate = dateString;
              }
            } catch (error) {
              // 解析出生日期出错
              console.error("解析出生日期失败:", error);
            }
          }
          if (data.Address) {
            // 身份证地址信息填入户口所在地和籍贯
            crudForm.formData.householdRegistration = data.Address;
            crudForm.formData.nativePlace = data.Address;
          }
          if (data.IdNumber) {
            crudForm.formData.idCardNo = data.IdNumber;
          }

          uni.showToast({
            title: "身份证正面信息识别成功",
            icon: "success",
          });
        } else if (cardType === "back") {
          // 验证是否确实是身份证反面（反面应该包含签发机关、有效期等信息）
          const hasBackInfo = data.IssuingAuthority || data.ValidPeriod;
          const hasFrontInfo =
            data.Name || data.IdNumber || data.Gender || data.BirthDate;

          if (!hasBackInfo && hasFrontInfo) {
            // 用户上传了身份证正面，但选择的是反面
            // 清理错误上传的图片数据
            crudForm.formData.idCardBackPhotoId = null;

            uni.showModal({
              title: "上传错误",
              content:
                "检测到您上传的是身份证正面，但当前需要上传身份证反面。图片已清除，请重新选择身份证反面照片上传。",
              confirmText: "重新上传",
              showCancel: false,
            });
            return;
          }

          if (!hasBackInfo) {
            // 无法识别出反面信息
            // 清理可能有问题的图片数据
            crudForm.formData.idCardBackPhotoId = null;

            uni.showModal({
              title: "识别异常",
              content:
                "无法从图片中识别出身份证反面信息。图片已清除，请重新上传。\n\n请确认并检查：\n1. 是否上传了正确的身份证反面\n2. 照片清晰完整\n3. 无反光、遮挡或模糊\n4. 身份证在照片中居中显示",
              confirmText: "我知道了",
              showCancel: false,
            });
            return;
          }

          // 身份证反面信息 - 直接使用接口返回的IdCardExpiryDate字段
          const idCardExpiryDate = (data as any).IdCardExpiryDate;
          if (idCardExpiryDate) {
            try {
              // 处理接口返回的IdCardExpiryDate字段
              let parsedDate: Date | null = null;
              const expiryDateStr = idCardExpiryDate.toString().trim();

              // 情况1: 直接是完整的日期时间格式 yyyy/MM/dd HH:mm:ss
              if (
                /^\d{4}\/\d{2}\/\d{2}\s+\d{2}:\d{2}:\d{2}$/.test(expiryDateStr)
              ) {
                parsedDate = new Date(expiryDateStr);
              }
              // 情况2: 只有日期部分 yyyy/MM/dd
              else if (/^\d{4}\/\d{2}\/\d{2}$/.test(expiryDateStr)) {
                parsedDate = new Date(expiryDateStr + " 00:00:00");
              }
              // 情况3: yyyy-MM-dd 格式
              else if (/^\d{4}-\d{2}-\d{2}$/.test(expiryDateStr)) {
                parsedDate = new Date(expiryDateStr + "T00:00:00");
              }
              // 情况4: yyyy.MM.dd 格式
              else if (/^\d{4}\.\d{2}\.\d{2}$/.test(expiryDateStr)) {
                const normalizedDate = expiryDateStr.replace(/\./g, "/");
                parsedDate = new Date(normalizedDate + " 00:00:00");
              }
              // 情况5: yyyyMMdd 格式
              else if (/^\d{8}$/.test(expiryDateStr)) {
                const year = expiryDateStr.substring(0, 4);
                const month = expiryDateStr.substring(4, 6);
                const day = expiryDateStr.substring(6, 8);
                parsedDate = new Date(`${year}/${month}/${day} 00:00:00`);
              }
              // 情况6: 其他格式，尝试直接解析
              else {
                parsedDate = new Date(expiryDateStr);
              }

              // 验证日期是否有效并设置
              if (parsedDate && !isNaN(parsedDate.getTime())) {
                // 检查日期是否超过50年（约18250天）
                const currentDate = new Date();
                const daysDifference = Math.abs(
                  (parsedDate.getTime() - currentDate.getTime()) /
                    (1000 * 60 * 60 * 24),
                );

                if (daysDifference > 18250) {
                  // 如果超过50年，保存原始日期但设置显示状态为"长期有效"
                  const year = parsedDate.getFullYear();
                  const month = String(parsedDate.getMonth() + 1).padStart(2, "0");
                  const day = String(parsedDate.getDate()).padStart(2, "0");
                  const dateString = `${year}-${month}-${day}`;
                  crudForm.formData.idCardExpiryDate = dateString; // 保存原始日期用于数据提交
                  idCardExpiryDisplayState.value = "long-term"; // 设置显示状态
                } else {
                  // 正常日期，使用识别到的日期
                  const year = parsedDate.getFullYear();
                  const month = String(parsedDate.getMonth() + 1).padStart(2, "0");
                  const day = String(parsedDate.getDate()).padStart(2, "0");
                  const dateString = `${year}-${month}-${day}`;
                  crudForm.formData.idCardExpiryDate = dateString;
                  idCardExpiryDisplayState.value = "normal"; // 重置显示状态为正常
                }
              }
            } catch (error) {
              // 解析身份证有效期出错
              console.error("解析身份证有效期失败:", error);
            }
          }

          // 兼容处理：如果IdCardExpiryDate字段不存在，尝试从ValidPeriod解析
          else if (data.ValidPeriod) {
            try {
              const validPeriod = data.ValidPeriod;
              if (validPeriod.includes("-") && !validPeriod.includes("长期")) {
                const endDate = validPeriod.split("-")[1];
                if (endDate) {
                  const endDateStr = endDate.trim();
                  let parsedDate: Date | null = null;

                  if (/^\d{4}\.\d{2}\.\d{2}$/.test(endDateStr)) {
                    const normalizedDate = endDateStr.replace(/\./g, "/");
                    parsedDate = new Date(normalizedDate + " 00:00:00");
                  } else if (/^\d{4}\/\d{2}\/\d{2}$/.test(endDateStr)) {
                    parsedDate = new Date(endDateStr + " 00:00:00");
                  }

                  if (parsedDate && !isNaN(parsedDate.getTime())) {
                    // 检查日期是否超过50年（约18250天）
                    const currentDate = new Date();
                    const daysDifference = Math.abs(
                      (parsedDate.getTime() - currentDate.getTime()) /
                        (1000 * 60 * 60 * 24),
                    );

                    if (daysDifference > 18250) {
                      // 如果超过50年，保存原始日期但设置显示状态为"长期有效"
                      const year = parsedDate.getFullYear();
                      const month = String(parsedDate.getMonth() + 1).padStart(2, "0");
                      const day = String(parsedDate.getDate()).padStart(2, "0");
                      const dateString = `${year}-${month}-${day}`;
                      crudForm.formData.idCardExpiryDate = dateString; // 保存原始日期用于数据提交
                      idCardExpiryDisplayState.value = "long-term"; // 设置显示状态
                    } else {
                      // 正常日期，使用识别到的日期
                      const year = parsedDate.getFullYear();
                      const month = String(parsedDate.getMonth() + 1).padStart(2, "0");
                      const day = String(parsedDate.getDate()).padStart(2, "0");
                      const dateString = `${year}-${month}-${day}`;
                      crudForm.formData.idCardExpiryDate = dateString;
                      idCardExpiryDisplayState.value = "normal"; // 重置显示状态为正常
                    }
                  }
                }
              }
            } catch (error) {
              // 从ValidPeriod解析有效期出错
              console.error("从ValidPeriod解析有效期失败:", error);
            }
          }

          uni.showToast({
            title: "身份证反面信息识别成功",
            icon: "success",
          });
        }
      } else {
        // 身份证识别失败时的详细提示
        let failureMessage = "身份证识别失败";
        if (response.Message) {
          failureMessage = response.Message;
        } else if (response.Code !== 200) {
          failureMessage = `识别服务异常(错误码:${response.Code})`;
        }

        // 清除失败的图片数据
        if (cardType === "front") {
          crudForm.formData.idCardFrontPhotoId = null;
        } else if (cardType === "back") {
          crudForm.formData.idCardBackPhotoId = null;
        }

        uni.showModal({
          title: "身份证识别失败",
          content: `${failureMessage}\n图片已清除，请重新上传。\n\n请确认并检查：\n1. 是否上传了正确的身份证${cardType === "front" ? "正面" : "反面"
            }\n2. 身份证照片清晰完整\n3. 无反光、遮挡或模糊\n4. 身份证在照片中居中显示\n\n您可以重新拍摄上传，或手动填写相关信息`,
          confirmText: "我知道了",
          showCancel: false,
        });
      }
    } catch (error) {
      uni.hideLoading();

      // 清除异常时的图片数据
      if (cardType === "front") {
        crudForm.formData.idCardFrontPhotoId = null;
      } else if (cardType === "back") {
        crudForm.formData.idCardBackPhotoId = null;
      }

      // 网络或系统错误时的详细提示
      uni.showModal({
        title: "身份证识别失败",
        content: `识别服务暂时不可用，可能是网络连接问题。图片已清除，请重新上传。\n\n建议操作：\n1. 确认上传的是身份证${cardType === "front" ? "正面" : "反面"
          }\n2. 检查网络连接\n3. 稍后重新尝试\n4. 或手动填写身份证信息`,
        confirmText: "我知道了",
        showCancel: false,
      });
    }
  };

  return {
    // 继承通用CRUD表单的所有功能
    ...crudForm,

    // 重写 initializeOptions 方法
    initializeOptions,

    // 应聘申请单信息专用方法
    loadInterviewDetail,
    createInterview,
    saveInterview,
    saveInterviewSimple,
    searchRecruitBills,

    // 身份证识别功能
    recognizeIdentityCard,

    // API数据转换方法
    convertFormDataToApiFormatForCreate,
    convertFormDataToApiFormatForEdit,

    // 字段映射
    fieldMapping,

    // 身份证有效期显示状态
    idCardExpiryDisplayState,
  };
}

// 辅助函数：获取性别文本
function getGenderText(value: number): string {
  const map: Record<number, string> = {
    1: "男",
    2: "女",
  };
  return map[value] || "";
}

